package com.wuchao.servlet143;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import java.io.IOException;

/**
 * @author 吴超66
 * @version 1.0
 * @date 2022/4/24 15:51
 */
@WebFilter(filterName = "FilterCodeUtf8",urlPatterns = "/demo71/*",
initParams ={@WebInitParam(name = "code",value = "utf-8")})
public class FilterCodeUtf8 implements Filter {
    //1设置初识编码规则
    private  String code;
    public void destroy() {
        this.code=null;
    }
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        //链式操作，做完之后不会组织web请求，链子一样，他还是继续
        String code = req.getCharacterEncoding();//拿到带过来的编码规则
        if(code==null||!code.equalsIgnoreCase(this.code)){
            req.setCharacterEncoding(this.code);
        } chain.doFilter(req, resp);
    }
    public void init(FilterConfig config) throws ServletException {//初始化编码
        String code=config.getInitParameter("code");//此时code是系统带来的规则
        //吧当前规则挂上去
        this.code=code;
    }

}
